package mina.forwhat.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hsqldb.lib.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import mina.forwhat.repository.GameCodeRepository;
import mina.forwhat.vo.GameCode;


@RestController
@Scope("prototype")
public class GameCodeController {
	
	public static final Logger log = LoggerFactory.getLogger(GameCodeController.class);
	@Autowired
	private GameCodeRepository gc;
	
	@GetMapping("/getGameCodeList")
	public Object getGameCodeList(@RequestParam("toolChose") String toolChose,@RequestParam("countTimes") Integer countTimes,@RequestParam(value = "onceCount",required = false) Integer onceCount) {
		log.info("游戏代码:查询收到的参数toolChose:"+toolChose+"  countTimes:"+ countTimes+"  onceCount:"+ onceCount);
		List<GameCode> game = new ArrayList<GameCode>();
		List<GameCode> gameGc = new ArrayList<GameCode>();
		
		if (GameCode.BACK_FRONT.equals(toolChose)){//从后往前
			Sort sort = new Sort(Sort.DEFAULT_DIRECTION.DESC, "createTime");
			game =  gc.findAll(sort);
		} else { //从前往后
			Sort sort = new Sort(Sort.DEFAULT_DIRECTION.ASC, "createTime");
			game =  gc.findAll(sort);
		}
		gameGc = game.subList(countTimes,game.size()-countTimes>onceCount?countTimes+onceCount:game.size());
		List<String> ss = new ArrayList<String>();
		ss.add(""+game.size());
		for(GameCode gg:gameGc){
			ss.add(gg.getCode());
		}
		return ss;
		
		
	}
	
	@PostMapping("/putGameCodeList")
	public void postGameCodeList(@RequestBody String data) {
		log.info("收到上传数据数据"+data);
		if(null==data || "".equals(data)) {
			return;
		}
		String regEx="[\\s~·`!！@#￥$%^……&*（()）\\-——\\-_=+【\\[\\]】｛{}｝\\|、\\\\；;：:‘'“”\"，,《<。.》>、/？?]";
		data =  data.replaceAll("[\u4e00-\u9fa5]+", " ");
		Pattern p = Pattern.compile(regEx);  
        Matcher m = p.matcher(data);  
		String dataCode[] = m.replaceAll(" ").split(" ");
		Set<String> ss= new HashSet<String>();
		for(String dd:dataCode){
			if(!StringUtil.isEmpty(dd.trim()) && dd.trim().length()==7){
				ss.add(dd.trim());
			}
		}
		for (String str : ss) {
			GameCode gcs = new GameCode();
			
			gcs.setCode(str);
			gcs.setCreateTime(new Date());
			gcs.setCreateUser("System");
			
			//log.info(str);
			
			try {
				gc.save(gcs);
				log.info("数据保存");
			} catch (Exception e) {
				log.info("可能出现重复异常");
			}
		}
		
	}
	
	/**
	 * 将不能用的兑换码设置一下
	 * @param code
	 * @param system
	 */
	@GetMapping("/updateUnusefulcode")
	public void updateUnusefulcode(@RequestParam("code") String code,@RequestParam("system") String system){
		log.info("数据更新没用的code" + code +" System : " +system);
		if("".equals(system.trim())) {
			return;
		}
		GameCode DbCode = new GameCode();
		if("Android".equals(system)) {
			DbCode =  gc.findByCodeAndAndroidUseful(code, 1);
			if(DbCode != null) {
				DbCode.setAndroidUseful(0);
			}else {
				return;
			}
		}else if("iOS".equals(system)) {
			DbCode = gc.findByCodeAndIosUseful(code, 1);
			if(DbCode != null) {
				DbCode.setIosUseful(0);
			}else {
				return;
			}
		}else {
			return;
		}
		gc.save(DbCode);
	}
	
	/**
	 * 只取得好用的数据
	 * @param toolChose
	 * @param countTimes
	 * @param onceCount
	 * @param system
	 * @return
	 */
	@GetMapping("/getGameCodeListUseful")
	public Object getGameCodeListUseful(@RequestParam("toolChose") String toolChose,
			@RequestParam("countTimes") Integer countTimes,
			@RequestParam(value = "onceCount",required = false) Integer onceCount,
			@RequestParam(value = "system") String  system
			) {
		log.info("游戏代码:查询收到的参数toolChose:"+toolChose+"  countTimes:"+ countTimes+"  onceCount:"+ onceCount + "system" +system );
		List<GameCode> game = new ArrayList<GameCode>();
		List<GameCode> gameGc = new ArrayList<GameCode>();
		
		if (GameCode.BACK_FRONT.equals(toolChose)){//从后往前
			Sort sort = new Sort(Sort.DEFAULT_DIRECTION.DESC, "createTime");
			game =  gc.findAll(sort);
			
		} else { //从前往后
			Sort sort = new Sort(Sort.DEFAULT_DIRECTION.ASC, "createTime");
			game =  gc.findAll(sort);
		}
		
		Iterator<GameCode> sListIterator = game.iterator();
		
		
		if("Android".equals(system)) {
			while (sListIterator.hasNext()) {
				GameCode gcEndtity = sListIterator.next();
				if (gcEndtity.getAndroidUseful() == 0) {
					sListIterator.remove();
				}
			}
		}else if("iOS".equals(system)) {
			while (sListIterator.hasNext()) {
				GameCode gcEndtity = sListIterator.next();
				if (gcEndtity.getIosUseful() == 0) {
					sListIterator.remove();
				}
			}
		}
        
		gameGc = game.subList(countTimes,game.size()-countTimes>onceCount?countTimes+onceCount:game.size());
		List<String> ss = new ArrayList<String>();
		ss.add(""+game.size());
		for(GameCode gg:gameGc){
			ss.add(gg.getCode());
		}
		return ss;
		
		
	}
	
		
//	@DeleteMapping("/deleGameCodeList")
//	public void delGameCodeList(@RequestParam("service") Integer service,@RequestParam("code") String code) {
//		if (service == 250){
//			return;
//		}
//		
//		System.out.println("接受到的删除数据_service"+service+"  "+"code"+code);
//		GameCode game =  gc.findByCode(code);
//		ServiceToCode sco = scss.findByGamecodeAndService(game, service);
//		scss.delete(sco);
//	}
}
